package com.a4studio.android.newsreader;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class MainActivity extends Activity {

	private final static String TAG = MainActivity.class.getSimpleName();
	private Calendar c = Calendar.getInstance();

	private Button timerButton;
	private Button keywordButton;
	private Button startServiceButton;
	private Button stopServiceButton;

	TextView timerSetting;
	TextView keywordSetting;

	EditText keywordEdit;

	Preferences prefs;
	
	Spinner spinner;
	
	private ArrayAdapter<String> resultChoice;
	private List<String> choices;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		prefs = new Preferences(this);
		timerButton = (Button) findViewById(R.id.timer_button);
		keywordButton = (Button) findViewById(R.id.keyword_button);
		startServiceButton = (Button)findViewById(R.id.start_service_button);
		stopServiceButton = (Button)findViewById(R.id.stop_service_button);

		timerSetting = (TextView) findViewById(R.id.timer_setting);
		keywordSetting = (TextView) findViewById(R.id.keyword_setting);
		
		spinner = (Spinner)findViewById(R.id.result_setting_spinner);
		initSpinner();

		loadTime();

		loadKeyword();
		loadResultNum();
		

		timerButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				c.setTimeInMillis(System.currentTimeMillis());
				int mHour = c.get(Calendar.HOUR_OF_DAY);
				int mMinute = c.get(Calendar.MINUTE);

				new TimePickerDialog(MainActivity.this,
						new TimePickerDialog.OnTimeSetListener() {

							@Override
							public void onTimeSet(TimePicker view,
									int hourOfDay, int minute) {
								// TODO Auto-generated method stub
								//long curTime = getTimeSetting();
								//c.setTimeInMillis(curTime);
								c.set(Calendar.HOUR_OF_DAY, hourOfDay);
								c.set(Calendar.MINUTE, minute);
								c.set(Calendar.SECOND, 0);
								c.set(Calendar.MILLISECOND, 0);
								prefs.setTimeSetting(c.getTimeInMillis());
								refreshTime(c.getTimeInMillis());

							}

						}, mHour, mMinute, true).show();
			}

		});

		keywordButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				LayoutInflater factory = LayoutInflater.from(MainActivity.this);
				final View keywordEditView = factory.inflate(
						R.layout.keyword_dialog, null);
				Builder mbuilder = new AlertDialog.Builder(MainActivity.this);
				mbuilder.setView(keywordEditView);
				keywordEdit = (EditText) keywordEditView
						.findViewById(R.id.keywordEditTex);
				keywordEdit.setText(getKeywordSetting());
				mbuilder.setTitle(R.string.keyword_alert_title);
				mbuilder.setPositiveButton(R.string.keyword_alert_positive,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								prefs.setKeywordSetting(keywordEdit.getText()
										.toString());
								refreshKeyword(keywordEdit.getText()
										.toString());
							}

						});

				mbuilder.setNegativeButton(R.string.keyword_alert_negative,
						null);
				mbuilder.show();
			}

		});
		
		startServiceButton.setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int period = 24*60*60*1000;
				long time = prefs.getTimeSetting();
				//TODO: 
				//give 3 minutes for a page to download in china for now
				//in fact, we need asynctask to handle this timing gracefully
				//we also need a time setting validation in timer pick to avoid
				//the dur allcated to download is too short to get complete content
				long pre_time = time - (prefs.getResultNumSetting()+1)*5*60*1000;
				startNewsFetchService(pre_time, period);		
				startRadioActivity(time, period);
				Toast.makeText(MainActivity.this, 
						R.string.start_service_toast, 
						Toast.LENGTH_LONG).show();
			}
			
		});
		
		stopServiceButton.setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				stopNewsFetchService();
				stopRadioActivity();
				Toast.makeText(MainActivity.this, 
						R.string.stop_service_toast, 
						Toast.LENGTH_LONG).show();
			}
			
		});

	}

	private String format(String x) {
		if (x.length() == 1)
			return "0" + x;
		return x;
	}

	private void loadTime() {
		long storedTime = prefs.getTimeSetting();

		if (storedTime == 0) {
			timerSetting.setText(R.string.timer_setting_not_exist);
		} else {
			c.setTimeInMillis(storedTime);
			int mHour = c.get(Calendar.HOUR_OF_DAY);
			int mMinute = c.get(Calendar.MINUTE);
			timerSetting.setText("" + format(mHour + "") + ":" + ""
					+ format(mMinute + ""));
		}
	}

	private void refreshTime(long storedTime) 
	{

		c.setTimeInMillis(storedTime);
		int mHour = c.get(Calendar.HOUR_OF_DAY);
		int mMinute = c.get(Calendar.MINUTE);
		timerSetting.setText("" + format(mHour + "") + ":" + ""
				+ format(mMinute + ""));
	}

	private void loadKeyword() {

		String keyword = prefs.getKeywordSetting();
		if (keyword.length() == 0) {
			keywordSetting.setText(R.string.keyword_setting_not_exist);
		} else {
			keywordSetting.setText(keyword);
		}
	}
	
	private void refreshKeyword(String keyword)
	{
		keywordSetting.setText(keyword);
	}

	private void initSpinner()
	{
		choices = new ArrayList<String>();
		for(int i = 0; i < 5; i ++)
		{
			choices.add((i+1)+"  buzz");	
		}
		
		resultChoice = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item,
				choices);
		
		resultChoice.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spinner.setAdapter(resultChoice);
		
		spinner.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				long index = arg0.getSelectedItemId();
				refreshResultNum((int)index);
				prefs.setResultNumSetting((int)index);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
	}
	
	private void loadResultNum()
	{
		
		int resultNum = prefs.getResultNumSetting();		
		spinner.setSelection(resultNum);
	}
	
	private void refreshResultNum(int resultNum)
	{
		spinner.setSelection(resultNum);
	}
	
	private long getTimeSetting() {
		long storedTime = prefs.getTimeSetting();

		if (storedTime == 0) {
			return System.currentTimeMillis();
		} else {
			return storedTime;
		}
	}

	private String getKeywordSetting() {
		String keyword = prefs.getKeywordSetting();
		return keyword;
	}
	
	private void startNewsFetchService(long time,int period)
	{
		Log.d(TAG, "startNewsFetchService");
		Intent service = new Intent(MainActivity.this,NewsFetchService.class);
		PendingIntent sender = PendingIntent.getService(MainActivity.this, 1, service, PendingIntent.FLAG_CANCEL_CURRENT);
		
		AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
		am.cancel(sender);
		
		am.setRepeating(AlarmManager.RTC_WAKEUP, time, period, sender);
		
	}
	
	private void startRadioActivity(long time,int period)
	{
		Log.d(TAG, "startRadioActivity");
		Intent service = new Intent(MainActivity.this,RadioActivity.class);
		PendingIntent sender = PendingIntent.getActivity(MainActivity.this, 1, service, PendingIntent.FLAG_CANCEL_CURRENT);
		
		AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
		am.cancel(sender);
		
		am.setRepeating(AlarmManager.RTC_WAKEUP, time, period, sender);
	}
	
	private void stopNewsFetchService()
	{
		Log.d(TAG, "stopNewsFetchService");
		Intent service = new Intent(MainActivity.this,NewsFetchService.class);
		PendingIntent sender = PendingIntent.getService(MainActivity.this, 1, service, PendingIntent.FLAG_CANCEL_CURRENT);
		
		AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
		am.cancel(sender);
		
		stopService(service);
	}
	
	private void stopRadioActivity()
	{
		Log.d(TAG, "stopRadioActivity");
		Intent service = new Intent(MainActivity.this,RadioActivity.class);
		PendingIntent sender = PendingIntent.getActivity(MainActivity.this, 1, service, PendingIntent.FLAG_CANCEL_CURRENT);
		
		AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
		am.cancel(sender);
		
		
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0,0,0,R.string.main_activity_view_news);
		
		return super.onCreateOptionsMenu(menu);
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		
		super.onOptionsItemSelected(item);
		switch(item.getItemId())
		{
		case 0:
			Bundle bundle = new Bundle();
			bundle.putBoolean(RadioActivity.VIEW_ONLY_KEY, true);
			Intent intent = new Intent(this,RadioActivity.class);
			intent.putExtras(bundle);
			startActivity(intent);
		}
		return true;
	}
}